<template>
	<view class="customizer" v-show="thskd">
		<!-- Close Button -->

		<!-- Main Preview -->
		<view class="preview-container" @click="uploadRefimg()">
			<image :src="mainImage" alt="Main" mode="aspectFill" class="preview-image" />
		</view>

		<!-- AI Type (placeholder) -->
		<view class="aitype">
			<!-- 固定的“模板”项 -->
			<view class="type-item fixed">
				<view class="type-item-image" style="padding:0 10rpx">
					<image src="https://material.senda360.com/wxa/aiLab/style2.png" mode="aspectFit" class="thumb" />
				</view>

			</view>

			<!-- 滚动区域：剩余四项 -->
			<scroll-view class="type-scroll" scroll-x scroll-with-animation :show-scrollbar="false" enhanced>

				<view class="type-item" v-for="(opt, i) in options" :key="i" @click="select(opt,i)">
					<view class="selectType" v-show="opt.show">
						<image src="/static/images/aishengc/选中.svg" mode="widthFix"></image>
					</view>
					<view class="type-item-image">
						<image :src="opt.icon.url" mode="aspectFit" class="thumb" />
					</view>
					<view class="type-item-label">{{ opt.label }}</view>
				</view>
			</scroll-view>

		</view>
		<!-- Options Toolbar -->


		<!-- Description Input -->
		<view class="description-box">
			<input type="text" v-model="description" placeholder="描述你想要创作的内容..." />
			<button class="upload-btn" @click="onUpload">
				<!-- 用这张图当按钮 -->
				<image src="https://material.senda360.com/wxa/aiLab/0001.png" mode="aspectFit" class="upload-icon" />
			</button>
		</view>
		<view class="">
			<progress :percent="percent" stroke-width="8" show-info></progress>
			<text>{{aiztai}}</text>

		</view>
		<!-- Placeholder Grid -->
		<view class="grid">
			<view v-for="(item,index) in imgListAi" :key="item" class="grid-item" @click="aishow(item.url)">
				<image :src="item.url" alt="" mode="widthFix" style="width: 100%;" />
			</view>
		</view>
	</view>
</template>

<script>
	import api from '../../api/Channel.js'
	import commonMixin from '@/mixins/qiLiuyun.js';
	import request from '../../api/index.js'
	import suffixAddress from '../../api/suffixAddress.js'
	export default {
		mixins: [commonMixin],
		name: 'ButtonCustomizer',
		data() {
			return {
				mainImage: 'https://material.senda360.com/wxa/aiLab/00060.png',
				selectedOption: 0,
				description: '',
				options: [],
				promptId: '',
				refImg: '',
				qiniuKey: '',
				socketTask: null, // WebSocket 任务对象
				reconnectTimer: null,
				reconnectInterval: 3000,
				logs: [],
				token: '',
				percent: 0,
				aiztai: '待处理',
				imgListAi: [],
				timerId: '',
				thskd:false
			};
		},
		onLoad() {
			this.token = uni.getStorageSync('token')
			
			const user = uni.getStorageSync('user');
			if (user && user.data && user.data.config && user.data.config.enableUploadCommodity) {
			  this.thskd = true;
			} else {
			  this.thskd = false;
			}

			
			
			this.eachType();
			this.openSocket()
			this.panduan()
		},
		onUnload() {
			uni.closeSocket({
				code: 1000,
				reason: '手动关闭连接',
				complete: () => {
					console.log('uni.closeSocket() 已调用');
					this.socketTask = null;
					clearInterval(this.timerId)
				}
			});
		},
		methods: {
			async panduan() {
				let obj = {
					url: api.ctrl + suffixAddress.add().userTasks,
					data: {
						pageNum: 1,
						pageSize: 1
					}
				}
				let res = await request(obj)
				let obja = {
					PENDING: '待处理',
					RUNNING: '执行中',
					SUCCEEDED: '已完成',
					FAILED: '失败'
				}
				this.aiztai = obja[res.data.list[0].status]
				if (res.data.list[0].status == 'RUNNING') {
					this.mainImage = res.data.list[0].image.url
				}
			},
			openSocket() {
				if (this.socketTask) {
					this.log('WebSocket 已经是打开状态')
					return;
				}
				let th = this
				this.socketTask = uni.connectSocket({
					url: api.wsUrl + this.token,
					success: () => {
						console.log('1111')
						th.timerId = setInterval(() => {
							// 这里调用你想要循环执行的方法，例如发送心跳
							this.socketTask.send({
								data: 1,
								success: () => {
									console.log('初始消息发送成功')
								},
								fail: err => {
									console.error('消息发送失败', err)
								}
							})
						}, 30 * 1000)
					},
					fail: (err) => {
						console.log(err)
					}
				})

				this.socketTask.onOpen(() => {
					this.socketTask.onMessage(msg => {
						let res = JSON.parse(msg.data)
						th.percent = res.progress
						let obj = {
							PENDING: '待处理',
							RUNNING: '执行中',
							SUCCEEDED: '已完成',
							FAILED: '失败'
						}
						th.aiztai = obj[res.status]
						if (res.progress == 100) {
							th.tasksaa(res)
						}
					})
				})
				this.socketTask.onError(e => {
					console.error('WS 错误', e)
					console.log(e)
					uni.showToast({
						title: '服务繁忙',
						icon: 'success',
						duration: 1500,
					})
				})

			},
			async tasksaa(resa) {
				let obj = {
					url: api.ctrl + suffixAddress.add().tasks,
					data: {
						taskId: resa.taskId
					}
				}
				let res = await request(obj)
				this.imgListAi = res.data.imgList
				this.mainImage = res.data.image.url
				uni.showToast({
					title: '生成成功',
					icon: 'success', // 'success' | 'loading' | 'none'
					duration: 1500 // 毫秒
				});

			},
			uploadRefimg() {
				if (this.aiztai == '执行中') {
					uni.showToast({
						title: '正在生成',
						icon: 'none', // 'success' | 'loading' | 'none'
						duration: 1500 // 毫秒
					});
					return
				}
				let th = this
				uni.chooseImage({
					count: 1,
					sourceType: ['camera', 'album'],
					crop: {
						width: 300,
						height: 300
					}, // 1:1 比例裁剪,
					success(res) {
						th.mainImage = res.tempFilePaths[0]
						th.qiNIuyun(res.tempFilePaths[0])
					},
					fail(res) {
						if (res.errNo == 10200) {
							th.pandxj()
						}

					}
				})
			},
			async qiNIuyun(imgs) {
				const key = await this.Tokenqiniu(imgs, 'ai-generate-ref')
				this.qiniuKey = key
			},
			async eachType() {
				let obj = {
					url: api.ctrl + suffixAddress.add().prompts
				}
				let res = await request(obj)
				this.options = res.data
				this.options.forEach(el => {
					el.show = false
				})
				// this.options[0].show = true
				// this.promptId = this.options[0].id 
			},
			async onUpload() {
				if (this.mainImage == 'https://material.senda360.com/wxa/aiLab/00060.png') {
					uni.showToast({
						title: '请选择图片',
						icon: 'none', // 'success' | 'loading' | 'none'
						duration: 1500 // 毫秒
					});
					return
				}

				if (this.promptId == '') {
					uni.showToast({
						title: '请选择模板',
						icon: 'none', // 'success' | 'loading' | 'none'
						duration: 1500 // 毫秒
					});
					return
				}

				if (this.aiztai == '执行中') {
					uni.showToast({
						title: '正在生成',
						icon: 'none', // 'success' | 'loading' | 'none'
						duration: 1500 // 毫秒
					});
					return
				}
				let obj = {
					url: api.ctrl + suffixAddress.add().generate,
					method: 'POST',
					data: {
						promptId: this.promptId,
						refImg: this.qiniuKey,
						refPrompt: this.description
					}
				}
				console.log(obj)
				let res = await request(obj)

				this.socketTask.send({
					data: 1,
					success: () => {
						console.log('初始消息发送成功')
					},
					fail: err => {
						console.error('消息发送失败', err)
					}
				})

				uni.showToast({
					title: '生成中',
					icon: 'success', // 'success' | 'loading' | 'none'
					duration: 1500 // 毫秒
				});
			},
			onClose() {
				uni.navigateBack();
			},
			select(item) {
				this.options.forEach(el => {
					el.show = false
				})

				item.show = true
				this.promptId = item.id
			},
			aishow(item) {
				uni.previewImage({
					current: item, // 当前显示哪张
					urls: [item] // 预览列表，可传多张
				});
			}
		}
	};
</script>

<style scoped>
	.customizer {
		position: relative;
		width: 720rpx;
		margin: auto;
		background: #fff;
		border: 2rpx solid #ccc;
		padding: 32rpx;
		box-sizing: border-box;
	}

	.close-btn {
		position: absolute;
		top: 16rpx;
		left: 16rpx;
		background: transparent;
		border: none;
		font-size: 36rpx;
		cursor: pointer;
	}

	.preview-container {
		text-align: center;
		margin-bottom: 32rpx;
	}

	.preview-image {
		width: 400rpx;
		height: 400rpx;
		object-fit: cover;
		background: #f5f5f5;
		border-radius: 16rpx;
	}

	.toolbar {
		display: flex;
		justify-content: space-between;
		margin-bottom: 32rpx;
	}

	.toolbar-item {
		flex: 1;
		text-align: center;
		padding: 16rpx;
		cursor: pointer;
		border: 2rpx solid transparent;
		border-radius: 8rpx;
	}

	.toolbar-item.active {
		border-color: #409eff;
		background: #e6f7ff;
	}

	.thumb {
		width: 96rpx;
		height: 96rpx;
		object-fit: cover;
		margin-bottom: 8rpx;
		border-radius: 8rpx;
		background: #fff;
	}

	.label {
		display: block;
		font-size: 24rpx;
	}

	.description-box {
		display: flex;
		margin-bottom: 32rpx;
		border: 2rpx solid #ccc;
		border-radius: 8rpx;
		overflow: hidden;
		height: 100rpx;
	}

	.description-box input {
		flex: 1;
		padding: 16rpx;
		border: none;
		outline: none;
		font-size: 24rpx;
	}

	.upload-btn {
		width: 80rpx;
		border: none;
		color: #fff;
		font-size: 28rpx;
		margin-right: 20rpx;
		cursor: pointer;
	}

	.grid {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		margin-top: 40rpx;
	}

	.grid-item {
		width: 32%;
		height: 160rpx;
		background: #f5f5f5;
		border-radius: 8rpx;
		margin-bottom: 16rpx;
	}

	.aitype {
		display: flex;
		margin-bottom: 32rpx;
		height: 260rpx;
	}

	.type-group {
		flex: 1;
		flex-direction: row;
		display: flex;
		justify-content: space-between;
	}

	.type-item {
		width: 200rpx;
		border-radius: 8rpx;
		position: relative;
		margin-right: 10rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.type-item-imgase {
		height: 150rpx;
		display: flex;
		justify-content: center;
	}

	.type-item-text {
		color: aliceblue;
		text-align: center;
		font-weight: 700;
		margin-bottom: 20rpx;
	}

	.option-scroll {
		padding: 20rpx 0;
	}

	/* 横向滚动容器 */
	.scroll {
		white-space: nowrap;
	}

	/* 隐藏原生滚动条（Webkit 内核） */
	.scroll::-webkit-scrollbar {
		width: 0;
		height: 0;
	}

	/* 隐藏 Firefox 滚动条 */
	.scroll {
		scrollbar-width: none;
	}

	/* 每一项 */
	.option-item {
		display: inline-flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 200rpx;
		margin-right: 16rpx;

		border-radius: 8rpx;
		padding: 16rpx 0;
	}

	/* 图片 */
	.option-image {
		width: 96rpx;
		height: 96rpx;
		margin-bottom: 8rpx;
		border-radius: 4rpx;
		object-fit: cover;
	}

	/* 文字标签 */
	.option-label {
		font-size: 24rpx;
		color: #333;
	}

	.aitype {
		flex-direction: row;
		display: flex;
		align-items: center;
		padding: 20rpx 0;
	}

	/* 第一项固定宽度 */
	.type-item.fixed {
		width: 200rpx;

		border-radius: 8rpx;
		margin-right: 16rpx;
		align-items: center;
		justify-content: center;
		display: flex;
		flex-direction: column;
		padding: 16rpx 0;
	}

	/* 滚动容器，剩余空间自适应宽度 */
	.type-scroll {
		flex: 1;
		white-space: nowrap;
		overflow-x: auto;
		white-space: nowrap;
		width: 100%;
		position: relative;
	}

	/* 隐藏滚动条 */
	.type-scroll::-webkit-scrollbar {
		width: 0;
		height: 0;
	}

	.type-scroll {
		scrollbar-width: none;
	}

	/* 每个可滚动项 */
	.type-item {
		display: inline-flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 200rpx;

		border-radius: 8rpx;
		margin-right: 16rpx;
		padding: 16rpx 0;
	}

	/* 缩略图 */
	.thumb {
		width: 200rpx;
		height: 300rpx;
	}

	/* 文本标签 */
	.type-item-label {
		font-size: 24rpx;
		color: #333;
	}

	.upload-icon {
		height: 100%;
		width: 200%;
	}

	.type-item.active {
		border: 2rpx solid #409eff;

	}

	.type-scroll::-webkit-scrollbar {
		width: 0 !important;
		height: 0 !important;
		background: transparent;
	}

	.selectType {
		position: absolute;
		top: 30rpx;
		right: 20rpx;
		width: 40rpx;
	}

	.selectType>image {
		width: 100%;
	}
</style>